package top.chaileilei.zookeeper.javaapi;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Description 创建节点相关
 * @Time 2019/1/28
 * @Author CHAILEILEI
 * @Weblog www.chaileilei.top
 */
public class JavaApiDemo2 implements Watcher{
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper;

    static {
        try {
            zooKeeper = new ZooKeeper("119.27.189.174:2181", 5000, new JavaApiDemo2());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception  {
        // simple3();
        simple4();
    }


    /**
     * @Description 创建节点，使用同步sync接口
     * @Author CHAILEILEI
     * @Time 2019/1/28
     * @Version V1.0.0
     */
    public static void simple3() throws Exception {
        countDownLatch.await();
        String s = zooKeeper.create("/tops", "chaileileis".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println(s);
    }
    public static void simple4() throws Exception{
        countDownLatch.await();
        zooKeeper.create("/zk-top-", "".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,
                new Demo3Callback(), "hahaha");
        zooKeeper.create("/zk-top-", "".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,
                new Demo3Callback(), "hahaha");
        zooKeeper.create("/zk-top-", "".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,
                new Demo3Callback(), "hahaha");
        Thread.sleep(1000);
    }

    static class Demo3Callback implements AsyncCallback.StringCallback {
        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            System.out.println("Create path result: [" + rc + ", " + path + ", "
                    + ctx + ", real path name: " + name);
        }
    }
    @Override
    public void process(WatchedEvent event) {
        System.out.println("receive watched event:" + event);
        if (Event.KeeperState.SyncConnected == event.getState()) {
            countDownLatch.countDown();
        }
    }
}
